package com.ddh.ddhsanguogame.interceptor;

import com.ddh.ddhsanguogame.utils.JwtUtil;
import com.ddh.ddhsanguogame.utils.UserContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 token
        String token = request.getHeader("Authorization");

        if (token != null && !token.isEmpty()) {
            // 将 token 存入 ThreadLocal
            String userId = JwtUtil.getUserIdFromToken(token);
            UserContextHolder.setUserId(Long.valueOf(userId));
            return true; // 返回 true 表示继续执行下一个拦截器或目标方法
        } else {
            // token 不存在或为空，返回 false 表示拦截请求
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后，但在视图渲染之前进行拦截
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求完成之后进行拦截（即在 DispatcherServlet 渲染了对应的视图之后）
        // 移除 ThreadLocal 中的 token
        UserContextHolder.removeUserId();
    }

}
